﻿using System;
using System.Collections.Generic;
using System.Text;
using Glue.Lib;
using Glue.Data;

namespace SqueezeboxBridge
{
    public class StreamCache
    {
        private static StreamCache _dictionary;

        /// <summary>
        /// Retrieve the current StreamCache
        /// </summary>
        public static StreamCache Current
        {
            get 
            {
                if (_dictionary == null)
                {
                    // First time

                    // Create dictionary instance
                    _dictionary = new StreamCache();

                    // Create tables (if necessary)
                    // Glo.CreateTables();
                }
                return _dictionary;
            }
        }

        /// <summary>
        /// Add a file to the file cache
        /// </summary>
        /// <param name="path">Path to file</param>
        /// <returns>File in cache</returns>
        public StreamCacheFile CacheFile(string path)
        {
            // Clean up cache
            Cleanup();

            StreamCacheFile file = StreamCacheFile.FindByPath(path);
            if (file == null)
            {
                // not found in cache
                file = StreamCacheFile.Create(path);
                file.Insert();
            }
            else
            {
                file.CacheDate = DateTime.Now;
                file.Update();
            }

            return file;
        }

        /// <summary>
        /// Retrieve cached file by Id
        /// </summary>
        /// <param name="id">File id</param>
        /// <returns>File in cache</returns>
        public StreamCacheFile Retrieve(string id)
        {
            return StreamCacheFile.FindById(id); 
        }

        /// <summary>
        /// Delete old items from the cache. 
        /// </summary>
        /// <remarks>
        /// At present, cache items are stored for 24h.
        /// </remarks>
        public void Cleanup()
        {
            Global.DataProvider.DeleteAll<StreamCacheFile>(Filter.Create("cachedate<@0", DateTime.Now.AddDays(-1)));
        }
    }
}
